import { track, trigger } from "./effect";
import { ReactiveFlags } from "./reactivity";

// 防止重复创建函数
const get = createGetter();
const set = createSetter();
const readonlyGet = createGetter(true);

function createGetter(isReadonly = false) {
  return function get(target: any, key: string | symbol) {
    // 当key的值为is_reactive时，返回isReadonly的值,来通知isReactive这个方法否为相应时对象
    if (key === ReactiveFlags.IS_REACTIVE) {
      return !isReadonly;
    }
    if (key === ReactiveFlags.IS_READONLY) {
      return isReadonly;
    }
    // 类似res = target[key]
    // 防止重复调用触发递归调用get
    const res = Reflect.get(target, key);

    // 收集依赖
    track(target, key);
    return res;
  };
}

function createSetter() {
  return function set(target: any, key: string | symbol, newValue: any): any {
    const res = Reflect.set(target, key, newValue);

    // TODO 触发依赖
    trigger(target, key);
    return res;
  };
}

export const mutableHandlers = { get, set };

export const readonlyHandlers = {
  get: readonlyGet,
  set(target: any, key: string | symbol, newValue: any): any {
    console.warn(`key: ${key as string} set fail, readonly`);
    return true;
  },
};
